package com.td.module.equipment.framework.core;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zhanghe
 * @date 2023/4/15
 */

@Slf4j
@Component
public class MqttClientBuilder {

    @Value("${mqtt.is-auto-reconnect:false}")
    private Boolean isAutoReconnect;

    @Resource
    private MqttCallBackContext mqttCallBackContext;

    public static ConcurrentHashMap<String, MqttClient> mqttClients = new ConcurrentHashMap<>();

    /**
     * 连接mqtt服务器
     * @param host
     * @param clientId
     * @param userName
     * @param passWord
     * @param cleanSession
     */
    public void buildMqttClient(String clientId, String host, String userName, String passWord, String topic, boolean cleanSession) {

        try {

            MqttClient mqttClient = new MqttClient(host, clientId, new MemoryPersistence());
            MqttConnectOptions options = new MqttConnectOptions();

            if (!StrUtil.isEmpty(userName)) {
                options.setUserName(userName);
            }

            if (!StrUtil.isEmpty(passWord)) {
                options.setPassword(passWord.toCharArray());
            }

//            options.setConnectionTimeout(60);
            options.setAutomaticReconnect(isAutoReconnect);
//            options.setCleanSession(cleanSession);
//            options.setKeepAliveInterval(60);

            AbsMqttCallBack callBack = mqttCallBackContext.getCallBack(clientId);
            if (callBack == null) {
                callBack = mqttCallBackContext.getCallBack("default");
            }
            callBack.setClientId(clientId);
            callBack.setMqttConnectOptions(options);

            mqttClient.setCallback(callBack);
            mqttClient.connect(options);

            if (!StrUtil.isEmpty(topic)) {
                mqttClient.subscribe(StringUtils.commaDelimitedListToStringArray(topic));
            }

            mqttClients.putIfAbsent(clientId, mqttClient);

        } catch (MqttException exception) {
            log.error("创建mqtt客户端失败！", exception);
            throw new RuntimeException(exception);
        }
    }



}
